#!/bin/bash 
set -e

TMP=${TMP:-/tmp/work}
LOG=${LOG:-$HOME/logs/stage3}
SRC=${SRC:-/sources}

name=ninja
version=1.10.2

rm -rf $TMP
mkdir -p $TMP $LOG

tar xf $SRC/$name-$version.tar.gz -C $TMP

{ time \
   {

    cd $TMP/$name-$version
    
    export NINJAJOBS="$(nproc)"
    
    sed -i '/int Guess/a \
      int   j = 0;\
      char* jobs = getenv( "NINJAJOBS" );\
      if ( jobs != NULL ) j = atoi( jobs );\
      if ( j > 0 ) return j;\
    ' src/ninja.cc
                
    python3 configure.py --bootstrap

    install -vm755 ninja /usr/bin/
    install -vDm644 misc/bash-completion /usr/share/bash-completion/completions/ninja
    install -vDm644 misc/zsh-completion  /usr/share/zsh/site-functions/_ninja

    }
} 2>&1 | tee $name.log
    
[ $PIPESTATUS = 0 ] && mv $name.log $LOG || exit $PIPESTATUS

rm -fr $TMP
